package com.linln.modules.api.service.impl;

import com.linln.common.data.PageSort;
import com.linln.common.enums.StatusEnum;
import com.linln.common.utils.EntityBeanUtil;
import com.linln.common.utils.StringUtil;
import com.linln.modules.api.domain.Project;
import com.linln.modules.api.repository.ProjectRepository;
import com.linln.modules.api.service.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cocia
 * @date 2020/08/03
 */
@Service
public class ProjectServiceImpl implements ProjectService {

    @Autowired
    private ProjectRepository projectRepository;

    /**
     * 根据ID查询数据
     * @param id 主键ID
     */
    @Override
    @Transactional
    public Project getById(Long id) {
        return projectRepository.findById(id).orElse(null);
    }

    @Override
    public List<Project> findAll() {
        return projectRepository.findAll();
    }

    /**
     * 获取分页列表数据
     * @param example 查询实例
     * @return 返回分页数据
     */
    @Override
    public Page<Project> getPageList(Example<Project> example) {
        // 创建分页对象
        PageRequest page = PageSort.pageRequest();
        return projectRepository.findAll(example, page);
    }

    /**
     * 保存数据
     * @param project 实体对象
     */
    @Override
    public Project save(Project project) {
        return projectRepository.save(project);
    }

    /**
     * 状态(启用，冻结，删除)/批量状态处理
     */
    @Override
    @Transactional
    public Boolean updateStatus(StatusEnum statusEnum, List<Long> idList) {
        return projectRepository.updateStatus(statusEnum.getCode(), idList) > 0;
    }

    @Override
    @Transactional
    public String match(List<Project> inProjects) {
        String warnMsg="";
        List<Project> saveProjects=new ArrayList<>();
        for (Project inProject:inProjects){
            List<Project> dbProjects=null;
            if (!StringUtil.isEmpty(inProject.getProjCode())){
                dbProjects=projectRepository.findByProjCode(inProject.getProjCode());
            }else {//没有任何标识字段，直接跳过
                continue;
            }

            Project dbProject=null;
            if (dbProjects.size()>=1){
                warnMsg+="项目编号=["+inProject.getProjCode()+"]，项目名称=["
                        +inProject.getTitle()+"]，存在多个查询结果，将只更新其中一个";
                dbProject=dbProjects.get(0);
                //fields表示需要复制的字段名称
                EntityBeanUtil.copyProperties(inProject,dbProject,"jz","qk");
                saveProjects.add(dbProject);
            }else {
                saveProjects.add(inProject);
            }
        }
        projectRepository.saveAll(saveProjects);
        return warnMsg;
    }

}